from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
from pyecharts.options import LabelOpts, TitleOpts

# 读取csv表中的每一行数据
f = open('E:/PythonBasicKnowledge/09 可视化（echarts）图表展示案例/柱状图/1960-2019全球GDP数据.csv', 'r',
         encoding='GB2312')
lines_data = f.readlines()
f.close()
# 第一行数据不需要👉删除
lines_data.pop(0)

# 将数据转换为字典存储
"""
{
    '1960': [
        ['中国', 100],
        ['日本', 222],
        ['美国', 555]
    ],
    '1961': [
        ['中国', 111],
        ['日本', 202],
        ['美国', 533]
    ]
    ...
}
"""
data_dict = {}
for line in lines_data:
    parts = line.split(',')
    year = str(parts[0])
    country = parts[1]
    gdp = float(parts[2])
    # print(F'年：{year}👉国家：{country}👉gdp：{gdp}')
    element = [country, gdp / 100000000]
    try:
        data_dict[year].append(element)
    except KeyError as e:
        print(F'新增加了年份: {year}')
        data_dict[year] = [element]

timeline = Timeline({
    'theme': ThemeType.LIGHT
})
keys = sorted(data_dict.keys())
for key in keys:
    country_gdp_list = data_dict[key]
    # 按照GDP值排序
    country_gdp_list.sort(key=lambda item: item[1], reverse=True)
    top8_list = country_gdp_list[:8:]

    # 循环前八名
    x_list = []
    y_list = []
    for e in top8_list:
        x_list.append(e[0])
        y_list.append(e[1])
    x_list.reverse()
    y_list.reverse()
    bar = Bar()
    bar.add_xaxis(x_list)
    bar.add_yaxis('GDP（亿）', y_list, label_opts=LabelOpts(position='right'))
    bar.reversal_axis()  # 反转
    bar.set_global_opts(TitleOpts(title=F'{key}年全球GDP排名前八'))
    timeline.add(bar, key)

# 时间线配置
timeline.add_schema(play_interval=2000,
                    is_timeline_show=True,
                    is_auto_play=True,
                    is_loop_play=True)
timeline.render('1996-2019GDP.html')
